package com.cfswt.tasksystem.controller;

import com.cfswt.tasksystem.mapper.*;
import com.cfswt.tasksystem.pojo.dto.MeetingDTO;
import com.cfswt.tasksystem.pojo.dto.MeetingDecisionDTO;
import com.cfswt.tasksystem.pojo.dto.MeetingRecordSortDTO;
import com.cfswt.tasksystem.pojo.vo.MeetingDecisionVO;
import com.cfswt.tasksystem.pojo.vo.ReminderVO;
import com.cfswt.tasksystem.pojo.entity.*;
import com.cfswt.tasksystem.pojo.vo.MeetingListVO;
import com.cfswt.tasksystem.pojo.vo.MeetingVO;
import com.cfswt.tasksystem.response.JsonResult;
import com.cfswt.tasksystem.security.CustomUserDetails;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.runtime.TaskRuntime;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.identity.Authentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "21.会议模块")
@RestController
@RequestMapping("/meeting")
public class MeetingController {
    @Autowired
    private MeetingMapper meetingMapper;
    @Autowired
    private ReminderMapper reminderMapper;
    @Autowired
    private MeetingAgendaMapper meetingAgendaMapper;
    @Autowired
    private MeetingAttendeesMapper meetingAttendeesMapper;
    @Autowired
    private MeetingRecordMapper meetingRecordMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TaskRuntime taskRuntime;
    @Autowired
    private TaskService taskService;
    @Autowired
    private MeetingCategoryMapper meetingCategoryMapper;
    @Autowired
    private MeetingAttachmentMapper meetingAttachmentMapper;
    @Autowired
    private ReminderUserMapper reminderUserMapper;
    @Autowired
    private SimpMessagingTemplate simpMessagingTemplate;
    @Autowired
    private MeetingDecisionMapper meetingDecisionMapper;
    @Autowired
    private TaskCompleteSummaryMapper taskCompleteSummaryMapper;
    @Autowired
    private TaskMapper taskMapper;

    @ApiOperation(value = "发布会议")
    @Transactional
    @PostMapping("/release/")
    public JsonResult releaseMeeting(@RequestBody MeetingDTO meetingDTO, @AuthenticationPrincipal CustomUserDetails userDetails) {
        meetingDTO.setPromoter(userDetails.getNickName());
        List<MeetingAttendees> meetingAttendeesList = meetingDTO.getMeetingAttendeesList();
        List<MeetingAgenda> meetingAgendaList = meetingDTO.getMeetingAgendaList();
        String processDefinitionKey = "Process_8";
        String bussinessKey = meetingDTO.getName() + "通知" + userDetails.getNickName();
        List<String> candidateUsers = meetingAttendeesList.stream()
                .map(MeetingAttendees::getName)
                .map(name -> userMapper.selectUserNameByNickName(name)) // 确保返回用户ID或用户名
                .collect(Collectors.toList());
        int candidateCount = meetingAttendeesList.size();
        Map<String, Object> variables = new HashMap<>();
        variables.put("attendees", candidateUsers);
        variables.put("candidateCount", candidateCount);
        String attendeesString = String.join(",", candidateUsers);
        variables.put("attendeesString", attendeesString);
        // 打印日志
        System.out.println("流程变量 - attendees: " + candidateUsers);
        System.out.println("流程变量 - candidateCount: " + candidateCount);
        System.out.println("流程变量 - attendeesString: " + attendeesString);
        Authentication.setAuthenticatedUserId(userDetails.getNickName());
        String processInstanceId = runtimeService.startProcessInstanceByKey(processDefinitionKey, bussinessKey, variables)
                .getProcessInstanceId();
        meetingDTO.setProcessInstanceId(processInstanceId);
        System.out.println(meetingDTO);
        meetingMapper.releaseMeeting(meetingDTO);
        for (MeetingAgenda meetingAgenda : meetingAgendaList) {
            meetingAgenda.setMeetingId(meetingDTO.getId());
            meetingAgendaMapper.insertAgenda(meetingAgenda);
        }
        for (MeetingAttendees meetingAttendees : meetingAttendeesList) {
            meetingAttendees.setMeetingId(meetingDTO.getId());
            meetingAttendeesMapper.insertAttendess(meetingAttendees);
        }
        List<MeetingAttachment> attachments = meetingDTO.getAttachment();
        for (MeetingAttachment attachment : attachments) {
            attachment.setMeetingId(meetingDTO.getId()).setCreateBy(userDetails.getNickName()).setCreateTime(new Date());
            meetingAttachmentMapper.insertAttachment(attachment);
        }
        ReminderVO reminderVO = new ReminderVO();
        reminderVO.setRemindTime(meetingDTO.getStartTime()); // 提醒时间
        reminderVO.setTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
        reminderVO.setRelatedId(meetingDTO.getId().toString());
        reminderVO.setType("会议通知");
        reminderVO.setSender(userDetails.getNickName());
        reminderVO.setTitle(meetingDTO.getName());
        reminderVO.setSummary(meetingDTO.getHost());
        reminderVO.setStatus(ReminderVO.Status.fromString("未读"));
        reminderMapper.insertReminder(reminderVO);
        Integer id = reminderVO.getId();
        for (MeetingAttendees attendee : meetingAttendeesList) {
            String name = attendee.getName();
            String userName = userMapper.selectUserNameByNickName(name);
            Integer userId = userMapper.selectIdByNickName(name);
            ReminderUser reminderUser = new ReminderUser();
            reminderUser.setUserId(userId);
            reminderUser.setReminderId(id);
            reminderUser.setCreateTime(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()));
            reminderUserMapper.insertReminderUser(reminderUser);
            System.out.println("Sending message to user: " + userName + " at /queue/meeting-notification");
            simpMessagingTemplate.convertAndSendToUser(userName, "/queue/meeting-notification", reminderVO);
            System.out.println(reminderVO);
        }
        return JsonResult.ok();
    }

    @ApiOperation(value = "显示会议列表")
    @GetMapping("/list")
    public JsonResult selectMeetingList() {
        List<MeetingListVO> meetingListVOS = meetingMapper.selectMeetingList();
        return JsonResult.ok(meetingListVOS);
    }

    @ApiOperation(value = "获取会议类型名称")
    @GetMapping("/category_name/{categoryId}")
    public JsonResult getCategoryName(@PathVariable Integer categoryId) {
        String categoryName = meetingCategoryMapper.getCategoryNameById(categoryId);
        return JsonResult.ok(categoryName);
    }

    @ApiOperation(value = "任务页里显示会议详细信息")
    @GetMapping("/detail_inTask/{taskId}")
    public JsonResult selectMeetingVO(@PathVariable String taskId) {
        String processInstanceId = taskRuntime.task(taskId).getProcessInstanceId();
        MeetingVO meetingVO = meetingMapper.selectMeetingByProcessInstanceId(processInstanceId);
        Integer meetingId = meetingVO.getId();
        List<MeetingAttendees> meetingAttendees = meetingAttendeesMapper.selectMeetingAttendeesByMeetingId(meetingId);
        List<MeetingAgenda> meetingAgenda = meetingAgendaMapper.selectMeetingAgendaByMeetingId(meetingId);
        List<MeetingAttachment> meetingAttachments = meetingAttachmentMapper.selectAttachmentByMeetingId(meetingId);
        List<MeetingAttachment> filteredAttachments = new ArrayList<>();
        for (MeetingAttachment meetingAttachment : meetingAttachments) {
            if ("会议发布时".equals(meetingAttachment.getSource())) {
                filteredAttachments.add(meetingAttachment);
            }
        }
        meetingVO.setMeetingAttachments(filteredAttachments);
        meetingVO.setMeetingAgendaList(meetingAgenda);
        meetingVO.setMeetingAttendeesList(meetingAttendees);
        return JsonResult.ok(meetingVO);
    }

    @ApiOperation(value = "列表页里显示会议详细信息")
    @GetMapping("/detail_inList/{meetingId}")
    public JsonResult selectMeetingVO(@PathVariable Integer meetingId) {
        MeetingVO meetingVO = meetingMapper.selectMeetingById(meetingId);
        List<MeetingAttendees> meetingAttendees = meetingAttendeesMapper.selectMeetingAttendeesByMeetingId(meetingId);
        List<MeetingAgenda> meetingAgenda = meetingAgendaMapper.selectMeetingAgendaByMeetingId(meetingId);
        List<MeetingAttachment> meetingAttachments = meetingAttachmentMapper.selectAttachmentByMeetingId(meetingId);
        List<MeetingAttachment> filteredAttachments = new ArrayList<>();
        for (MeetingAttachment meetingAttachment : meetingAttachments) {
            if ("会议发布时".equals(meetingAttachment.getSource())) {
                filteredAttachments.add(meetingAttachment);
            }
        }
        meetingVO.setMeetingAttachments(filteredAttachments);
        meetingVO.setMeetingAgendaList(meetingAgenda);
        meetingVO.setMeetingAttendeesList(meetingAttendees);
        return JsonResult.ok(meetingVO);
    }

    @ApiOperation(value = "参会人提交会议议案信息")
    @PostMapping("/record/")
    public JsonResult insertMeetingRecords(@RequestBody MeetingRecord meetingRecord, @AuthenticationPrincipal CustomUserDetails userDetails) {
        if (meetingRecord.getId() != null) {
            meetingRecordMapper.updateMeetingRecord(meetingRecord);
        } else {
            meetingRecord.setCreateTime(new Date());
            meetingRecordMapper.insertMeetingRecords(meetingRecord);
        }
        return JsonResult.ok();
    }

    @ApiOperation(value = "保存会议决策内容")
    @PostMapping("/decision/")
    public JsonResult addMeetingDecisions(@RequestBody List<MeetingDecisionDTO> meetingDecisionDTOS) {
        for (MeetingDecisionDTO meetingDecisionDTO : meetingDecisionDTOS) {
            if (meetingDecisionMapper.selectMeetingDecisionByMeetingIdAndRecordId(meetingDecisionDTO.getMeetingId(), meetingDecisionDTO.getRecordId())) {
                meetingDecisionDTO.setId(meetingDecisionMapper.selectDecisionIdByMeetingIdAndRecordId(meetingDecisionDTO.getMeetingId(), meetingDecisionDTO.getRecordId()));
                meetingDecisionMapper.updateMeetingDecisionById(meetingDecisionDTO);
            } else {
                meetingDecisionDTO.setCreateTime(new Date());
                meetingDecisionMapper.insertMeetingDecisions(meetingDecisionDTO);
            }
        }
        return JsonResult.ok();
    }

    @ApiOperation(value = "保存普通会议工作决策内容")
    @PostMapping("/usual_decision/")
    public JsonResult addUsualMeetingDecisions(@RequestBody List<MeetingDecisionDTO> meetingDecisionDTOS) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (MeetingDecisionDTO meetingDecisionDTO : meetingDecisionDTOS) {
            int decisionId;
            meetingDecisionDTO.setCreateTime(new Date());
            meetingDecisionMapper.insertMeetingDecisions(meetingDecisionDTO);
            decisionId = meetingDecisionDTO.getId(); // 假设插入后ID会自动回填
            // 组装 rowId 和 decisionId 的映射
            Map<String, Object> map = new HashMap<>();
            map.put("rowId", meetingDecisionDTO.getRowId());
            map.put("decisionId", decisionId);
            resultList.add(map);
        }
        return JsonResult.ok(resultList);
    }

    @ApiOperation(value = "显示会议决策内容")
    @GetMapping("/decision/{meetingId}")
    public JsonResult selectMeetingDecisions(@PathVariable Integer meetingId) {
        List<MeetingDecisionVO> meetingDecisionVOS = meetingDecisionMapper.selectMeetingDecisionsByMeetingId(meetingId);
        for (MeetingDecisionVO meetingDecisionVO : meetingDecisionVOS) {
            Integer taskId = meetingDecisionVO.getTaskId();
            if (taskId != null) {
                CfswtTask cfswtTask = taskMapper.selectTaskInfoById(taskId);
                meetingDecisionVO.setEndTime(cfswtTask.getEndTime());
                meetingDecisionVO.setReportBy(cfswtTask.getReportBy());
            }
        }
        System.out.println(meetingDecisionVOS);
        return JsonResult.ok(meetingDecisionVOS);
    }

    @ApiOperation(value = "班子会议显示上次会议决策内容以及完成情况")
    @GetMapping("/last_decision/{meetingId}")
    public JsonResult selectLastMeetingDecisions(@PathVariable Integer meetingId) {
        int lastMeetingId = meetingMapper.selectLastMeetingId(meetingId);
        List<MeetingDecisionVO> meetingDecisionVOS = meetingDecisionMapper.selectMeetingDecisionsByMeetingId(lastMeetingId);
        for (MeetingDecisionVO meetingDecisionVO : meetingDecisionVOS) {
            List<TaskCompleteSummary> taskCompleteSummaries = taskCompleteSummaryMapper.selectCompleteSummariesByTaskId(meetingDecisionVO.getTaskId());
            System.out.println("完成情况数据：" + taskCompleteSummaries);
            meetingDecisionVO.setCompleteSummaries(taskCompleteSummaries);
        }
        System.out.println(meetingDecisionVOS);
        return JsonResult.ok(meetingDecisionVOS);
    }

    @ApiOperation(value = "管理员提交或更新上次会议工作完成情况")
    @PostMapping("/last_decision/complete/")
    public JsonResult updateLastMeetingComplete(@RequestBody TaskCompleteSummary taskCompleteSummary) {
        int i = taskCompleteSummaryMapper.selectCountTaskCompleteSummary(taskCompleteSummary.getId());
        if (i > 0) {
            taskCompleteSummaryMapper.updateTaskCompleteSummary(taskCompleteSummary);
        } else {
            taskCompleteSummaryMapper.addTaskCompleteSummary(taskCompleteSummary);
        }
        return JsonResult.ok();
    }


    @ApiOperation(value = "更新会议议案顺序")
    @PostMapping("/record/sort/")
    public JsonResult updateMeetingRecordSort(@RequestBody List<MeetingRecordSortDTO> meetingRecordSortDTOS) {
        for (MeetingRecordSortDTO meetingRecordSortDTO : meetingRecordSortDTOS) {
            meetingRecordMapper.updateMeetingRecordSortBatch(meetingRecordSortDTO);
        }
        return JsonResult.ok();
    }

    @ApiOperation(value = "显示会议议案信息")
    @GetMapping("/record/{meetingId}")
    public JsonResult selectRecordByMeetingId(@PathVariable Integer meetingId) {
        List<MeetingRecord> meetingRecords = meetingRecordMapper.selectRecordByMeetingId(meetingId);
        System.out.println(meetingRecords);
        return JsonResult.ok(meetingRecords);
    }

    @ApiOperation(value = "显示会议记录信息中记录人的记录信息")
    @GetMapping("/record/{meetingId}/{recorder}")
    public JsonResult selectRecordByMeetingId(@PathVariable Integer meetingId, String recorder) {
        List<MeetingRecord> meetingRecords = meetingRecordMapper.selectRecordByMeetingIdAndRecorder(meetingId, recorder);
        return JsonResult.ok(meetingRecords);
    }

    @ApiOperation(value = "参会人确认会议信息")
    @PostMapping("/confirm/{meetingId}")
    public JsonResult confirmMeetingRecords(@PathVariable Integer meetingId, @AuthenticationPrincipal CustomUserDetails userDetails) {
        String processInstanceId = meetingMapper.selectProcessInstanceIdBymeetingId(meetingId);
        System.out.println(processInstanceId);
        org.activiti.engine.task.Task task = taskService.createTaskQuery().taskAssignee(userDetails.getUsername()).processInstanceId(processInstanceId).singleResult();
        System.out.println(task.getName());
        if ("参会人提交会议议题".equals(task.getName())) {
            Authentication.setAuthenticatedUserId(userDetails.getNickName());
            taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(task.getId()).build());
            System.out.println("完成任务: ID=" + task.getId() + ", Assignee=" + userDetails.getUsername());
        }
        return JsonResult.ok();
    }


}
